﻿// ... 其它using ...
using B.MESUI.Login.A_Public.Service;
using B.MESUI.Login.ProdManagement.DTO;
using B.MESUI.Login.ProdManagement.Services;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.ProdManagement.WorkOrder
{
    public partial class AddWorkOrder : DevExpress.XtraEditors.XtraForm
    {
        private ComboBoxEdit _ruleComboBox;
        private SimpleButton _generateCodeButton;
        private TextEdit _previewCodeTextBox;
        private LabelControl _ruleLabel;
        private LabelControl _previewLabel;
        private string _generatedCode = string.Empty;
        public AddWorkOrder()
        {
            InitializeComponent();
            this.CenterToParent();
            this.Load += AddWorkOrder_Load;
            this.PRODUCTION_LINE.SelectedIndexChanged += PRODUCTION_LINE_SelectedIndexChanged;
            this.addworkordersimpleButton1.Click += addworkordersimpleButton1_Click;
        }


        /// <summary>
        /// 窗体加载事件 - 自动加载编码规则并生成预览，同时加载产线数据
        /// </summary>
        private async void AddWorkOrder_Load(object sender, EventArgs e)
        {
            try
            {
                // 直接根据默认规则生成预览并赋值到CODEID
                string defaultRule = "AddWorkOrder"; // 可根据实际业务调整
                string previewCode = await CodeGenService.PreviewCodeAsync(defaultRule);
                CODEID.Text = previewCode;
                var tasks = new List<Task>
                {
                    LoadProductionLines()
                };
                await Task.WhenAll(tasks);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"初始化失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 加载产线数据
        /// </summary>
        private async Task LoadProductionLines()
        {
            try
            {
                var productionLines = await ProjectLineService.GetProductionLinesAsync();
                PRODUCTION_LINE.Properties.Items.Clear();
                foreach (var line in productionLines)
                {
                    PRODUCTION_LINE.Properties.Items.Add(line.linE_NAME);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载产线数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 产线下拉框选中事件
        /// </summary>
        private void PRODUCTION_LINE_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PRODUCTION_LINE.SelectedIndex >= 0)
            {
                string selectedLineName = PRODUCTION_LINE.Text;
                // 可扩展：选中产线后的处理逻辑
            }
        }

        /// <summary>
        /// 添加工单按钮点击事件 - 保存工单
        /// </summary>
        private async void addworkordersimpleButton1_Click(object sender, EventArgs e)
        {



            string code = await CodeGenService.GenerateCodeAsync("AddWorkOrder");
            string preview = await CodeGenService.PreviewCodeAsync("AddWorkOrder");

            CODEID.Text = code;
            // 验证其他必填字段
            if (string.IsNullOrEmpty(WORKORDER_TYPE.Text) ||
                string.IsNullOrEmpty(PRODUCT_DATA.Text) ||
                string.IsNullOrEmpty(PROCESS_ROUTE.Text) ||
                string.IsNullOrEmpty(PRODUCTION_LINE.Text))
            {
                XtraMessageBox.Show("请填写完整的工单信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                addworkordersimpleButton1.Enabled = false;
                // 构造工单请求
                var workOrderRequest = new AddWorkOrderRequest
                {
                    codeid = CODEID.Text,
                    workordeR_TYPE = WORKORDER_TYPE.Text,
                    producT_DATA = PRODUCT_DATA.Text,
                    procesS_ROUTE = PROCESS_ROUTE.Text,
                    productioN_LINE = PRODUCTION_LINE.Text,
                    worK_STATUS = WORK_STATUS.Text,
                    starT_TIME = START_TIME.DateTime,
                    enD_TIME = END_TIME.DateTime,
                    numbeR_COL = int.TryParse(NUMBER_COL.Text, out int num) ? num : 0,
                    procesS_PROGRESS = PROCESS_PROGRESS.Text,
                    isorskip = radioButton1.Checked ? 1 : 0,
                    attachment = ATTACHMENT.Text,
                    workordeR_DESC = WORKORDER_DESC.Text,
                    sourcE_WORKER = SOURCE_WORKER.Text
                };

                // 保存工单
                bool workOrderSuccess = await WorkOrderService.AddWorkOrderAsync(workOrderRequest);

                if (workOrderSuccess)
                {
                    XtraMessageBox.Show("工单保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("工单保存失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"保存过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                addworkordersimpleButton1.Enabled = true;
            }
        }
    }
}